package top.jiug.k_pdf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import top.jiug.k_pdf.entity.User;
import top.jiug.k_pdf.service.UserService;
import top.jiug.k_pdf.util.PdfUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Controller
public class JiugController {

    @Resource
    private UserService userService;

    @RequestMapping(value = "/export")
    public void export(String[] args, HttpServletResponse response) throws IOException {
        //导出文件名
        String title="keffett";

        response.setContentType("text/plain;charaset=utf-8");
        response.setContentType("application/vnd.ms-pdf");
        response.setHeader("Content-Disposition", "attachment; filename="+title+".pdf");

        //获取输出流
        OutputStream out = response.getOutputStream();

        PdfUtil pdfUtil=new PdfUtil();
        List<String[]> data=getData();
        pdfUtil.generatePDF(out,data);

        out.close();

    }

    private List<String[]> getData() {
        List<String[]> data=new ArrayList<>();
        data.add(new String[]{"姓名","密码","年龄"});

        List<User> users = userService.queryUserList();
        for (int i = 0; i < users.size(); i++) {
            String[] body=new String[data.get(0).length];
            body[0]=users.get(i).getUsername();
            body[1]=users.get(i).getPassword();
            body[2]=users.get(i).getAge()+"";
            data.add(body);
        }
        return data;
    }


}
